package manipulador;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Xpath {

	public static void main(String[] args) throws XPathExpressionException, SAXException, IOException, ParserConfigurationException {
		//String wsdlUrl = "http://localhost:8080/HelloWeb/services/Hello?wsdl";
		String wsdlUrl = "http://soap.amazon.com/schemas2/AmazonWebServices.wsdl";		
		Xpath consumidor = new Xpath();
		String wsdlString = consumidor.parseWsdlToString(wsdlUrl);
		consumidor.parseStringToXml(wsdlString);
		IOArquivo.salvarArquivo("wsdl2.txt", wsdlString, false);
	}
	
	/**
	 * Faz a conexão com o web service, captura o wsdl e coloca seu
	 * contéudo em uma string
	 * @param wsdlUrl endereço do wsdl
	 * @return contéudo do wsdl em formato string
	 * @throws MalformedURLException, IOException
	 */
	public  String parseWsdlToString(String wsdlUrl){        
		try {
			URL url = new URL(wsdlUrl);
	        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
	        BufferedReader input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
	        StringBuilder sbuilder = new StringBuilder();
	        String linha = null;          
	        while( (linha = input.readLine()) != null ){
	        	sbuilder.append(linha + '\n');
	        	
	        }        
	        input.close();
	        urlConnection.disconnect();
	        return sbuilder.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	/**
	 * Transforma o wsdl em formato string num formato xml e através do xpath 
	 * buscas os nós desejados imprimindo seus atributos
	 * @param wsdlString wsdl em formato string
	 * @throws XPathExpressionException, ParserConfigurationException, SAXException, IOException
	 */
	public void parseStringToXml(String wsdlString) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException{
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
	    domFactory.setNamespaceAware(true);
	    DocumentBuilder docBuilder = domFactory.newDocumentBuilder();
	    InputSource is = new InputSource( new StringReader(wsdlString));
	    Document doc = docBuilder.parse(is);

	    XPath xpath = XPathFactory.newInstance().newXPath();
	    xpath.setNamespaceContext(new PersonalNamespaceContext());
	    XPathExpression expr = xpath.compile("/wsdl:definitions/wsdl:portType/wsdl:operation/*");

	    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
	    for (int i = 0; i < nodes.getLength(); i++) {
	    	NamedNodeMap elemento= nodes.item(i).getAttributes();		
	    	System.out.print(nodes.item(i).getNodeName());
	    	//System.out.print(" \t Name: " + elemento.getNamedItem("name").getNodeValue());
	    	System.out.println("\t message: " + elemento.getNamedItem("message").getNodeValue());
	    }   
	}
	
}
